import socket, wx, threading
from faker import Faker  # faker随机生成地址或者名字
import wx

class Client(wx.Frame):

    def __init__(self):
        # 实例属性
        self.client_socket = None
        self.name = Faker("zh_CN").name()  #客户端名字
        self.isConnected = False

        wx.Frame.__init__(self, None, title=f"{self.name}聊天客户端", size=(400, 600), pos=(200, 200))
        self.pl = wx.Panel(self, size=(600, 600), pos=(0, 0))
        btn_add = wx.Button(self.pl, label="加入聊天室", pos=(10, 10), size=(150, 30))
        btn_stop = wx.Button(self.pl, label="退出聊天室", pos=(200, 10), size=(150, 30))
        btn_clear = wx.Button(self.pl, label="清空", pos=(10, 500), size=(150, 30))
        btn_send = wx.Button(self.pl, label="发送", pos=(200, 500), size=(150, 30))

        # 接收消息的文本框
        self.recv_text = wx.TextCtrl(self.pl, pos=(0, 60), size=(400, 200), style=wx.TE_READONLY | wx.TE_MULTILINE)
        # 发送消息的文本框
        self.send_text = wx.TextCtrl(self.pl, pos=(0, 280), size=(400, 200), style=wx.TE_MULTILINE)

        self.Bind(wx.EVT_BUTTON, self.add, btn_add)
        self.Bind(wx.EVT_BUTTON, self.stop, btn_stop)
        self.Bind(wx.EVT_BUTTON, self.clear, btn_clear)
        self.Bind(wx.EVT_BUTTON, self.send, btn_send)

    def add(self, event):
        if not self.isConnected:
            self.isConnected = True
            # 连接服务器
            self.client_socket = socket.socket()
            self.client_socket.connect(("127.0.0.1", 8998))
            send_data = f"{self.name}".encode("utf8")
            self.client_socket.send(send_data)
            # 创建线程
            main_thread = threading.Thread(target=self.recv_data)
            # 设置守护线程
            main_thread.daemon = True
            # 启动线程
            main_thread.start()

    def recv_data(self):
        while self.isConnected:
            accept_data = self.client_socket.recv(1024)
            self.recv_text.AppendText(accept_data.decode("utf8") + "\n")

    def stop(self, event):
        send_data = "断开连接".encode("utf8")
        self.client_socket.send(send_data)

    def clear(self, event):
        self.send_text.Clear()

    def send(self, event):
        if self.isConnected:
            send_data = self.send_text.GetValue().encode("utf8")
            if send_data != "":
                self.client_socket.send(send_data)
                self.send_text.Clear()


# 程序入口
if __name__ == '__main__':
    app = wx.App()
    client = Client()
    client.Show()

    app.MainLoop()
